'''
成人全面重疾保险
'''
import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "成人全面重疾保险"

    # 生产产品数据
    def genProductInfo(self):
        plan = {

            "planA": {
                # 年龄段
                "year": [str(i) for i in range(18, 41)],
                # 性别
                "gender": ["M", "F"],
                # 计划
                "plan": ["全面款"],
                # 三十种重大疾病
                "majorDisease": ["50000"],
                # 意外身故/伤残
                "accidentalDie": ["100000"],
                # 癌症医疗
                "cancerMedic": ["50000"]

            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(18, 41)],
                # 性别
                "gender": ["M", "F"],
                # 计划
                "plan": ["热销款"],
                # 三十种重大疾病
                "majorDisease": ["200000"],
                # 意外身故/伤残
                "accidentalDie": ["500000"],
                # 癌症医疗
                "cancerMedic": ["200000"]

            },
            "planC": {

                # 年龄段
                "year": [str(i) for i in range(18, 41)],
                # 性别
                "gender": ["M", "F"],
                # 计划
                "plan": ["自定义"],
                # 三十种重大疾病
                "majorDisease": ["50000", "100000", "200000"],
                # 意外身故/伤残
                "accidentalDie": ["100000", "200000", "500000"],
                # 癌症医疗
                "cancerMedic": ["0", "50000", "100000", "200000"]
            }

        }

        for k in plan:

            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["plan"], plan[k]["majorDisease"],
                             plan[k]["accidentalDie"], plan[k]["cancerMedic"]):

                if v[2] == "全面款":
                    # 十五种轻重疾
                    slightDisease = "15000"
                elif v[2] == "热销款":
                    # 十五种轻重疾
                    slightDisease = "60000"

                else:

                    if v[3] == "50000":

                        slightDisease = "15000"

                    elif v[3] == "100000":

                        slightDisease = "30000"

                    else:

                        slightDisease = "60000"

                # 写入数据库
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(

                    v[0], v[1], v[2], v[3], slightDisease, v[4], v[5]
                ))
                self.mysql._conn.commit()
                print(

                    domain[self.name]["insert_sql"].format(

                        v[0], v[1], v[2], v[3], slightDisease, v[4], v[5]
                    )

                )

    # 执行爬虫
    def requestJson(self, dt=None):

        data = {"planClass": "0", "amountFormList": [
            {"majorDisease": 50000, "slightDisease": 15000, "accidentalDie": 100000, "cancerMedic": 50000},
            {"majorDisease": 200000, "slightDisease": 60000, "accidentalDie": 500000, "cancerMedic": 200000},
            {"majorDisease": dt["majorDisease"], "slightDisease": dt["slightDisease"],
             "accidentalDie": dt["accidentalDie"], "cancerMedic": dt["cancerMedic"]}],
                "beginDate": "2020-01-15", "insType": "M",
                "birthDate": "{year}-01-05".format(year=str(2019 - int(dt["year"]))), "sexCode": dt["gender"]}

        payload = json.dumps(data)

        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

        if r.status_code == 200:
            # 更新热销款
            quoteResult1 =(r.json()["quoteResult1"]["toaUserPremium"])

            SQL = 'UPDATE `成人全面重疾保险` SET price = "' + quoteResult1 + '" , state = 2 WHERE year = "' + dt[
                "year"] + '" AND plan = "全面款" AND  gender = "'+dt["gender"]+'"'

            self.mysql.cursor.execute(SQL)
            self.mysql._conn.commit()
            print("产品信息更新成功:", dt["year"])

            quoteResult2 = (r.json()["quoteResult2"]["toaUserPremium"])


            SQL = 'UPDATE `成人全面重疾保险` SET price = "' + quoteResult2 + '" , state = 2 WHERE year = "' + dt[
                "year"] + '" AND plan = "热销款" AND  gender = "'+dt["gender"]+'"'

            self.mysql.cursor.execute(SQL)
            self.mysql._conn.commit()
            print("产品信息更新成功:", dt["year"])

            quoteResult3 = (r.json()["quoteResult3"]["toaUserPremium"])

            data = {

                "name":self.name,
                "id":dt["id"],
                "price":quoteResult3
            }
            self.mysql.updatePrice( data )

        else:

            pass

    def main(self):

        while True:

            SQL = 'SELECT * FROM `成人全面重疾保险` WHERE plan = "自定义" and state = 0 ORDER BY RAND() limit 1 '

            self.mysql.cursor.execute(SQL)

            dt = self.mysql.cursor.fetchone()


            if not dt:

                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)

